import Vue from 'vue'
import CustomMessage from './message.vue'
let MsgConstructor = Vue.extend(CustomMessage) // 生成vc的构造函数
let instant
let instants = []
let seed = 0
let zIndex = 9999
const Message = (options) => {
	if (typeof options === 'string') {
		options = {
			msg: options
		}
		
	}
    //用户传的关闭时的回调函数
	let userOnClose = options.onClose
    // 给每个vc 绑定唯一id
	let id = `my_message_${seed++}`

    //触发定时器结束关闭消息的回调，在这里可移除数组intstants中关闭的消息
	options.onClose = function() { 
		Message.close(id, userOnClose)
	}

    // 构造一个vc实例对象(生成一条消息)
	instant = new MsgConstructor({ 
		data: options
	})
	instant.id = id
    //实例挂载
	instant.$mount()
	document.body.appendChild(instant.$el)
	instant.visible = true
	let topOffset = options.offset || 20
	if (instants.length === 0) {
		instant.topOffset = 20
	}
	instants.forEach(item =>{
        topOffset += item.$el.offsetHeight + 16
    } ) // 设置style的top值
	instant.topOffset = topOffset
	instant.$el.style.zIndex = zIndex++
	instants.push(instant)
	return instant
}
//  四种不同类型的消息
let types = ['info', 'success', 'warning', 'error']
types.forEach(type => {
	Message[type] = (options) => {
		if (typeof options === 'object') {
			return Message({
				type,
				...options
			})
		}
		return Message({
			type,
			msg: options
		})
	}

})


Message.close = (id, userOnClose) => {
	let removeHeight;
    let len = instants.length
    let index = -1
	for (let i = 0; i < len; i++) {
        if (id === instants[i].id) {
            removeHeight = instants[i].$el.offsetHeight;
            index = i;
            if (typeof userOnClose === 'function') {
                userOnClose(instants[i]);
            }
            instants.splice(i, 1);
            break;
        }
    }

    if(len <= 1 || index === -1 || index > instants.length - 1) return

    for (let i = index; i < len - 1 ; i++) {
        let dom = instants[i].$el;
        dom.style['top'] = parseInt(dom.style['top'], 10) - removeHeight - 16 + 'px';
    }
}

Message.closeAll = () => {
    for (let i = instants.length - 1; i >= 0; i--) {
        instants[i].close();
    }
};

export default Message
